package com.example.demo.tool.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.Scanner;

public class ChatClient {

    public static void main(String[] args) throws InterruptedException {

        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        // 处理器
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    // 编码器
                                    .addLast(new MyMessageDecoder())
                                    // 解码器
                                    .addLast(new MyMessageEncoder())
                                    .addLast(new ChatClientHandler());
                            ;
                        }
                    });

            // 连接服务器
            ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 9000).sync();

            // 拿到通道
            Channel channel = channelFuture.channel();

            System.out.println("== 客户端" + channel.localAddress() +"启动成功====");

            // 输入框
//            Scanner scanner = new Scanner(System.in);
//            while (scanner.hasNextLine()) {
//                String msg = scanner.nextLine();
//                channel.writeAndFlush(msg);
//            }
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                MyMessageProtocol messageProtocol = new MyMessageProtocol();
                byte[] bytes = msg.getBytes(CharsetUtil.UTF_8);
                messageProtocol.setContent(bytes);
                messageProtocol.setLen(bytes.length);
                //通过 channel 发送到服务器端
                channel.writeAndFlush(messageProtocol);
            }


        } finally {
            group.shutdownGracefully();
        }
    }
}

